const inquirer = require("inquirer");
const { boolChoies } = require("../config");
const ora = require("ora");
const t = require("../config/dict");
const config = require("../mfo.config.js");
const { error, log, exeCommandSpawn, packageManager } = require("./utils");
const path = require("path");

module.exports = (context) => {
  return inquirer
    .prompt([
      {
        name: "projectStartBuildVaild",
        message: t(context.lang, "开始构建验证") + "?",
        default: "yes",
        pageSize: 3,
        type: "rawlist",
        choices: [...boolChoies],
      },
    ])
    .then((answers) => {
      if (answers.projectStartBuildVaild === "yes") {
        return new Promise((resolve, reject) => {
          const spinner = ora("Starting ...");
          spinner.start();
          const cwd = path.resolve(process.cwd(), context.metadata.projectDir);
          packageManager(cwd)
            .run(config.template.vaild.split(" "), {
              cwd,
            })
            /* exeCommandSpawn(config.template.vaild, {
            cwd: path.resolve(process.cwd(), context.metadata.projectDir),
            shell: true,
          }) */
            .then(() => {
              spinner.text = [
                t(context.lang, "成功"),
                t(context.lang, "。"),
              ].join(" ");
              spinner.succeed();
              context.metadata.projectStartBuildVaild =
                answers.projectStartBuildVaild;
              resolve(context);
            })
            .catch((err) => {
              spinner.fail();
              error(err);
              log("warn", {
                message: [
                  t(context.lang, "本地服务启动失败"),
                  t(context.lang, "。"),
                ].join(" "),
              });
              resolve(context);
            });
        });
      } else {
        return context;
      }
    })
    .catch((err) => {
      return Promise.reject(err);
    });
};
